﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Linq;
using Android.Util;
using LeePong.Game.Shapes;

namespace LeePong.Game
{
    public class CoordinatesMover
    {
        public static void MoveAsync(Coordinates current, Coordinates target, int speed, Action finished, RunToken Token = null)
        {

            if (Token == null)
            {
                Log.D("----", "created??");
                Token = new RunToken();
            }

            var thread = new Thread(() =>
            {
                MoveAction(current, target, speed, finished, Token);
            });
            thread.Start();
        }

        private static void MoveAction(Coordinates current, Coordinates target, int speed, Action finished, RunToken Token)
        {
            var path = GetPath(current, target);
            foreach (var coord in path)
            {
                if (Token.IsCancelled)
                {
                    //   Log.D("----", "cancelled:" + path.IndexOf(coord));
                    return;
                }
                Thread.Sleep(speed);
                current.X = coord.X;
                current.Y = coord.Y;
            }

            current.X = target.X;
            current.Y = target.Y;

            finished();
        }

        private static List<Coordinates> GetPath(Coordinates current, Coordinates target)
        {
            var length = 10.0f;
            var rawPath = new List<Coordinates>();
            var xfrag = (target.X - current.X) / length;
            var yfrag = (target.Y - current.Y) / length;

            var coord = new Coordinates();
            coord.X = current.X + xfrag;
            coord.Y = current.Y + yfrag;
            rawPath.Add(coord);

            for (int i = 0; i < length - 1; i++)
            {
                var before = rawPath[i];
                var temp = new Coordinates();
                temp.X = before.X + xfrag;
                temp.Y = before.Y + yfrag;
                rawPath.Add(temp);
            }

            return rawPath;
        }


        public static void Move(Coordinates current, int angle, float step)
        {
            var piAngle = Math.PI * (angle / 180.0f);
            current.X = (float)(current.X + (step * Math.Cos(piAngle)));
            current.Y = (float)(current.Y + (step * Math.Sin(piAngle)));
        }
    }
}
